# Create your views here.
from django.http import HttpResponse
from django.template import Context,loader
from django.shortcuts import render_to_response
from django.contrib.auth.decorators import login_required

from game.locations.models import map, location
from game.combat.models import combat
from game.monster.models import group
from game.encounter.views import showEncounter
import random

def showLocation(request, locName):
    loc = location.objects.get(name = locName)
    if loc.linkToMap is not None:
        return renderMap(request, loc.linkToMap.id)
    elif loc.encounters:
        encounter = loc.chooseEncounter()
        return showEncounter(request, encounter)

def renderMap(request, mapID):
    response = HttpResponse()
    c = Context()
    t = loader.get_template('locations/map.html')
    
    try:
        mapToShow = map.objects.get(id=mapID)
        locations = location.objects.filter(map=mapToShow)
        mapArray = {}
        for y in xrange(0, mapToShow.hight):
            mapArray[y]= {}
            for x in xrange(0, mapToShow.width):
                try:
                    #See if there is a location at this point
                    loc = locations.get(xCord=x, yCord=y)
                    if loc.isActive():
                        #Location is active for the player
                        url = None
                        url = loc.get_absolute_url()
                        mapArray[y][x] = [loc.activeImage, url]
                    else:
                        #Location has not yet been opened
                        mapArray[y][x] = [loc.inactiveImage, None]
                except Exception, e:
                    #No location, use the map's default node
                    mapArray[y][x] = [mapToShow.baseNode, None]
                 #   return HttpResponse(t.render(c))
        c['map'] = mapArray
        return HttpResponse(t.render(c))
           
    except Exception, e:

        return response
